class TopicsController < ApplicationController
	load_and_authorize_resource only: [:new,:create,:edit]
	before_action :isadmin?, only: [:suggest]
	def new
		@topic=Topic.new
		if params[:node].present?
			@topic.node_id=params[:node]
			@node=Node.find_by_id(params[:node])
		end
	end

	def create
		@topic=Topic.new(topic_params)
		@topic.user_id= current_user.id unless current_user.blank?

		@topic.node_id=params[:node]||params[:topic][:node_id]
		if @topic.save
			redirect_to(topic_path(@topic.id), notice: '话题创建成功')
		else
			render action: 'new'
		end

	end

	def index
		@topics=Topic.all.order(created_at: :desc).paginate(page: params[:page],per_page: 13).to_a

	end

	def edit
		@topic=Topic.find(params[:id])
		@node=@topic.node

	end

	def update
		@topic=Topic.find(params[:id])
		@topic.title=params[:topic][:title]
		@topic.body=params[:topic][:body]
		if @topic.save
			redirect_to(topic_path(@topic.id),notice: "更新成功")
		else
			render action: "edit"
		end
	end

	def show
		@topic=Topic.includes(:user).find(params[:id])

		@replies=Reply.where(topic_id: @topic.id).order(:id).all
	end

	def excellent
		@topics=Topic.excellent_topics.order(id: :desc).includes(:user).paginate(page: params[:page],per_page: 20)
		render action: 'index'

	end

	def node
		@node=Node.find(params[:id])
		@topics=@node.topics.paginate(page: params[:page],per_page: "13")
		render action: "index"
	end

	#加精
	def suggest
		@topic=Topic.find(params[:id])
	  @topic.update_attribute(:excellent,1)
		redirect_to @topic
	end
	# 取消加精
	def unsuggest
		@topic=Topic.find(params[:id])
		@topic.update_attribute(:excellent,0)
		redirect_to @topic
	end


	private
		def topic_params
			params.require(:topic).permit(:body,:title,:node_id)
		end
		def isadmin?
			admin?(current_user)
		end
end
